//
//  CNKISearchViewController.m
//  CNKICommunity
//
//  Created by wei on 17/3/13.
//  Copyright © 2017年 CNKI. All rights reserved.
//

#import "CNKISearchViewController.h"
#import "CNKISearchResultViewController.h"
#import "CNKISuggestViewController.h"

#define Search_LeftMargin 10//默认左边距
#define Search_TopMargin 10//默认上边距



@interface CNKISearchViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,UIScrollViewDelegate>

@property(nonatomic,weak)UITableView *baseTableview;//用于搜索历史和热门搜索的底部视图
@property(nonatomic,strong)NSMutableArray *searchHistoryArr;

@property(nonatomic,weak)UIView *searchHistoryTagsViews;//历史标签视图
@property(nonatomic,weak)UIView *searchHistoryView;//历史视图
@property(nonatomic,weak)UILabel *searchHistoryLabel;//历史标题

@property(nonatomic,assign)BOOL keyBoardShowing;//键盘是否打开
@property(nonatomic,assign)CGFloat keyBoardHeight;//键盘高度

@property(nonatomic,weak)CNKISuggestViewController *SuggestViewController;//搜索建议页面



@end

@implementation CNKISearchViewController

//懒加载

-(CNKISuggestViewController *)SuggestViewController
{
    if (!_SuggestViewController)
    {
        CNKISuggestViewController *SuggestVC =[[CNKISuggestViewController alloc]initWithStyle:UITableViewStyleGrouped];
        SuggestVC.view.frame = CGRectMake(0, 64, SCREENWIDTH, SCREENHEIGHT);
        SuggestVC.view.hidden = YES;
        SuggestVC.view.backgroundColor = self.baseTableview.backgroundColor;
        __weak typeof(self)weakself = self;
        SuggestVC.SuggestBlock = ^(UITableViewCell *selectCell){
            
            weakself.searchBar.text = selectCell.textLabel.text;
            [self searchBarSearchButtonClicked:weakself.searchBar];
        };
        [self.view addSubview:SuggestVC.view];
        [self addChildViewController:SuggestVC];
        _SuggestViewController = SuggestVC;
    }
    return _SuggestViewController;
}


-(UITableView *)baseTableview
{
    if (!_baseTableview)
    {
        UITableView *baseTview = [[UITableView alloc]initWithFrame:self.view.bounds style:UITableViewStyleGrouped];
        baseTview.delegate = self;
        baseTview.dataSource = self;
        baseTview.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:baseTview];
        _baseTableview = baseTview;
    }
    return _baseTableview;
}
-(NSMutableArray *)searchHistoryArr
{
    if (!_searchHistoryArr)
    {
        _searchHistoryArr = [NSMutableArray arrayWithArray:[NSKeyedUnarchiver unarchiveObjectWithFile:self.searchHistoryCachesPath]];
    }
    return _searchHistoryArr;
}
-(UIButton *)clearBtn
{
    if (!_clearBtn)
    {
        UIButton *clear = [UIButton buttonWithType:UIButtonTypeCustom];
        clear.titleLabel.font = self.searchHistoryLabel.font;
        [clear setBackgroundImage:[UIImage imageNamed:@"empty"] forState:UIControlStateNormal];
        [clear addTarget:self action:@selector(emptySearchHistoryDidClick) forControlEvents:UIControlEventTouchUpInside];
        clear.width = Search_LeftMargin + 10;
        clear.height = Search_LeftMargin + 10;
        clear.x = self.HotsearchHeadView.width - clear.width;
        clear.centerY = self.searchHistoryLabel.centerY;
        [self.HotsearchHeadView addSubview:clear];
        _clearBtn = clear;
    }
    return _clearBtn;
}
-(UILabel *)searchHistoryLabel
{
    if (!_searchHistoryLabel)
    {
        UILabel *mylabel = [self setUpTitleLabelstyle:@"搜索历史"];
        [self.HotsearchHeadView addSubview:mylabel];
        _searchHistoryLabel = mylabel;
    }
    return _searchHistoryLabel;
}
//清空所有历史记录
-(void)emptySearchHistoryDidClick
{
    [self.searchHistoryArr removeAllObjects];
    [NSKeyedArchiver archiveRootObject:self.searchHistoryArr toFile:_searchHistoryCachesPath];
    [self setCNKIBottomSearchHistoryStyle:CNKISearchHistoryStyleCell];
}
//赋值建议数组
-(void)setSearchSuggestions:(NSArray<NSString *> *)searchSuggestions
{
    _searchSuggestions = searchSuggestions;
    self.SuggestViewController.searchSuggestion = [searchSuggestions copy];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setCNKIBottomSearchHistoryStyle:CNKISearchHistoryStyleCell];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
}

-(instancetype)init
{
    self = [super init];
    if (self)
    {
        [self setUp];
    }
    return self;
}
-(instancetype)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [self setUp];
    }
    return self;
}

#pragma mark--初始化
-(void)setUp
{
    
    // 搜索历史缓存路径
    self.searchHistoryCachesPath = CNKISEARCH_SEARCH_HISTORY_CACHE_PATH;
    self.searchHistoryNum = 20;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self baseTableview];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyBordDidShow:) name:UIKeyboardDidShowNotification object:nil];
    
    //右键取消键设置
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancelDidclick)];
    
    self.showSearchSuggestWhenSearchTextChanged = YES;//隐藏建议view
    
    
    //创建搜索框 底部view
    UIView *titleView = [UIView new];
    titleView.x = Search_LeftMargin * 0.5;
    titleView.y = Search_TopMargin;
    titleView.width = SCREENWIDTH - 64 - Search_LeftMargin;
    titleView.height = 30;
    titleView.backgroundColor = [UIColor whiteColor];
    
    //搜索框
    UISearchBar *NewSearchBar = [[UISearchBar alloc]initWithFrame:titleView.bounds];
    [titleView addSubview:NewSearchBar];
    self.navigationItem.titleView = titleView;
    NewSearchBar.translatesAutoresizingMaskIntoConstraints = NO;
    [NewSearchBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleView.mas_left);
        make.right.equalTo(titleView.mas_right);
        make.top.equalTo(titleView.mas_top);
        make.bottom.equalTo(titleView.mas_bottom);
    }];
    NewSearchBar.placeholder = @"请输入您的搜索词汇";
    NewSearchBar.backgroundImage = [UIImage imageNamed:@"clearImage"];
    NewSearchBar.delegate = self;
    _searchBar = NewSearchBar;
    
    //设置头部 热门搜索
    UIView *headView = [[UIView alloc]init];
    UIView *contentView = [[UIView alloc]init];
    contentView.x = Search_LeftMargin * 1.5;
    contentView.y = Search_TopMargin;
    contentView.width = SCREENWIDTH - contentView.x * 2;
    [headView addSubview:contentView];
    
    UILabel *itemLabel = [self setUpTitleLabelstyle:@"热门搜索"];
    [contentView addSubview:itemLabel];
    _HotsearchLabel = itemLabel;
    
    //设置热门搜索的容器
    UIView *tagView = [[UIView alloc]init];
    tagView.width = contentView.width;
    tagView.y = CGRectGetMaxY(_HotsearchLabel.frame) + Search_TopMargin;
    [contentView addSubview:tagView];
    _HotsearchHeadTagView  = tagView;
    _HotsearchHeadView = contentView;
    _HotsearchHeadView.userInteractionEnabled = YES;
    self.baseTableview.tableHeaderView = headView;
    
    //设置底部(清除历史搜索)
    UIView *footerView = [UIView new];
    footerView.width = SCREENWIDTH;
    footerView.height = 30;
    UILabel *clearLabel = [UILabel new];
    clearLabel.textColor = [UIColor darkGrayColor];
    clearLabel.font = [UIFont systemFontOfSize:13];
    clearLabel.userInteractionEnabled = YES;
    clearLabel.text = @"清除浏览历史";
    clearLabel.textAlignment = NSTextAlignmentCenter;
    clearLabel.x = 0;
    clearLabel.y = 0;
    clearLabel.width = SCREENWIDTH;
    clearLabel.height = 30;
    [clearLabel addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(emptySearchHistoryDidClick)]];
    [footerView addSubview:clearLabel];
    
    self.baseTableview.tableFooterView = footerView;
    
    
}

//创建标题的格式
-(UILabel*)setUpTitleLabelstyle:(NSString*)text
{
    UILabel *titlelabel = [[UILabel alloc]init];
    titlelabel.text = text;
    titlelabel.font = [UIFont systemFontOfSize:13];
    titlelabel.textColor = TitleTagColor;
    [titlelabel sizeToFit];
    titlelabel.x = 0;
    titlelabel.y = 0;
    return titlelabel;
    
}

-(void)cancelDidclick
{
    [self.searchBar resignFirstResponder];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
//键盘显示弹出
-(void)keyBordDidShow:(NSNotification*)noti
{
    NSDictionary *dic = noti.userInfo;
    self.keyBoardHeight = [dic[UIKeyboardFrameEndUserInfoKey] CGRectValue].size.height;
    //调整搜索建议内边距
    self.SuggestViewController.tableView.contentInset = UIEdgeInsetsMake(-30, 0, self.keyBoardHeight + 30, 0);
    self.keyBoardShowing = YES;
}


#pragma mark--工厂模式初始化
+(CNKISearchViewController *)setupSearchVCWithHotSearches:(NSArray<NSString *> *)HotSearches searchPlaceholder:(NSString *)placeHolder
{
    CNKISearchViewController *searchVC = [[CNKISearchViewController alloc]init];
    searchVC.hotSearchArr = HotSearches;
    searchVC.searchBar.text = placeHolder;
    return searchVC;
}

+(CNKISearchViewController *)setupSearchVCWithHotSearches:(NSArray<NSString *> *)HotSearches searchPlaceholder:(NSString *)placeHolder Searchblock:(CNKISearchBlock)searchblock
{
    CNKISearchViewController *searchVC = [self setupSearchVCWithHotSearches:HotSearches searchPlaceholder:placeHolder];
    searchVC.DidSearchBlock = searchblock;
    return searchVC;
}


#pragma mark--setter方法
-(void)setHotSearchArr:(NSArray *)hotSearchArr
{
    _hotSearchArr = hotSearchArr;
    if (_hotSearchArr.count != 0)
    {
        self.baseTableview.tableHeaderView.hidden = NO;
        self.HotsearchHeadView.hidden = NO;
        self.HotsearchHeadTagView.hidden = NO;
        
    }
    
    //刷新历史搜索页面
    [self setCNKIBottomSearchHistoryStyle:CNKISearchHistoryStyleCell];
}
-(void)setCNKIBottomSearchHistoryStyle:(CNKISearchHistoryStyle)CNKIBottomSearchHistoryStyle
{
    
    if (self.searchHistoryArr.count == 0||!self.searchHistoryArr)
    {
        //没有搜索数据
        self.searchHistoryLabel.hidden = YES;
        self.clearBtn.hidden = YES;
    }
    else
    {
        //有搜索数据
        self.searchHistoryLabel.hidden = NO;
        self.clearBtn.hidden = YES;
    }
    //设置并刷新控件
    [self setUpHistorySearchTags];
}
-(void)setUpHistorySearchTags
{
    
    [self addAndLayoutTagsWithTagContentView:self.HotsearchHeadTagView tagText:self.hotSearchArr];
}
-(void)addAndLayoutTagsWithTagContentView:(UIView*)contentview tagText:(NSArray<NSString *> *)tagarr
{
    //删除子控件
    [contentview.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    for (int i = 0; i < tagarr.count; i++)
    {
        UILabel *label = [self labelWithTitle:tagarr[i]];
        [label addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(TagDidClick:)]];
        [contentview addSubview:label];
        
    }
    
    //经典模式 乱序排法
    CGFloat SubWidth = 0;
    CGFloat SubHeight = 0;
    CGFloat NumCol = 0;
    CGFloat NumRow = 0;
    
    for (int i = 0; i < contentview.subviews.count; i++)
    {
        UILabel *mySubview = contentview.subviews[i];
        if (mySubview.width > contentview.width)
        {
            mySubview.width = contentview.width;
        }
        if (SubWidth + mySubview.width + Search_LeftMargin * NumCol > contentview.width )
        {
            //换行
            mySubview.x = 0;
            mySubview.y = (SubHeight += mySubview.height) + Search_LeftMargin * ++NumRow;
            SubWidth = mySubview.width;
            NumCol = 1;
        }else
        {
            mySubview.x = (SubWidth += mySubview.width) - mySubview.width + Search_LeftMargin * NumCol;
            mySubview.y = SubHeight + Search_LeftMargin * NumRow;
            NumCol++;
        }
        
    }
    //设置contentview的高度
    contentview.height = CGRectGetMaxY(contentview.subviews.lastObject.frame);
    //设置tableviewheader和次级view(包含热门标签 标题和历史标题 清除键)的高度
    if (!self.searchHistoryLabel.hidden)
    {
        self.searchHistoryLabel.y = self.hotSearchArr.count > 0 && self.hotSearchArr ? CGRectGetMaxY(contentview.frame) + Search_LeftMargin * 1.5 : 0;
        self.clearBtn.y = self.searchHistoryLabel.y;

        self.baseTableview.tableHeaderView.height = self.HotsearchHeadView.height = CGRectGetMaxY(self.searchHistoryLabel.frame) + Search_LeftMargin * 2;
    }
    else
    {
       self.baseTableview.tableHeaderView.height = self.HotsearchHeadView.height = CGRectGetMaxY(self.HotsearchHeadTagView.frame) + Search_LeftMargin * 2;
    }
    self.baseTableview.tableHeaderView.hidden = NO;
    //重新赋值, 注意：当操作系统为iOS 9.x系列的tableHeaderView高度设置失效，需要重新设置tableHeaderView
    [self.baseTableview setTableHeaderView:self.baseTableview.tableHeaderView];

    [self.baseTableview reloadData];
    
}
-(void)TagDidClick:(UIGestureRecognizer*)gr
{
    UILabel *label = (UILabel *)gr.view;
    self.searchBar.text = label.text;
    
    //同点击搜索按钮
    [self searchBarSearchButtonClicked:self.searchBar];
    
}

-(UILabel*)labelWithTitle:(NSString *)title
{
    UILabel *label = [[UILabel alloc]init];
    label.userInteractionEnabled = YES;
    label.font = [UIFont systemFontOfSize:12];
    label.text = title;
    label.textColor = [UIColor grayColor];
    label.backgroundColor = [UIColor lightGrayColor];
    label.layer.cornerRadius = 3;
    label.clipsToBounds = YES;
    label.textAlignment = 1;
    [label sizeToFit];
    label.width += 20;
    label.height += 14;
    return label;
}


#pragma mark--SearchDelegate
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    if (self.DidSearchBlock)
    {
        self.DidSearchBlock(self,searchBar,searchBar.text);
    }
    
    [self saveHistoryDataDidclickSearchBtn];
}

-(void)saveHistoryDataDidclickSearchBtn
{
    UISearchBar *mybar = self.searchBar;
    [mybar resignFirstResponder];
    
    //先删除 再刷新
    [self.searchHistoryArr removeObject:mybar.text];
    [self.searchHistoryArr insertObject:mybar.text atIndex:0];
    
    //限定20条
    if (self.searchHistoryArr.count > self.searchHistoryNum)
    {
        [self.searchHistoryArr removeLastObject];
    }
    //保存信息
    [NSKeyedArchiver archiveRootObject:self.searchHistoryArr toFile:_searchHistoryCachesPath];
    [self.baseTableview reloadData];


    //跳转页面
    //[self handleResultPage];
}
-(void)handleResultPage
{
    //跳转搜索结果页面
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.navigationController pushViewController:[CNKISearchResultViewController new] animated:YES];
    });
}
#pragma mark--TableViewDelegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    self.baseTableview.tableFooterView.hidden = !self.searchHistoryArr.count;
    return self.searchHistoryArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellId = @"CNKIHistoryCellId";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell)
    {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        cell.textLabel.textColor = TitleTagColor;
        cell.textLabel.font = [UIFont systemFontOfSize:14];
        cell.backgroundColor = [UIColor clearColor];
        
        //关闭按钮
        UIButton *closedBtn = [[UIButton alloc]init];
        closedBtn.size = CGSizeMake(cell.height, cell.height);
        [closedBtn setImage:[UIImage imageNamed:@"close"] forState:UIControlStateNormal];
        [closedBtn addTarget:self action:@selector(deleteHistorycell:) forControlEvents:UIControlEventTouchUpInside];
        cell.accessoryView = closedBtn;
        
        //添加分割线
        UIImageView *lineView = [[UIImageView alloc]init];
        lineView.image = [UIImage imageNamed:@"cell-content-line"];
        lineView.x = Search_LeftMargin;
        lineView.width = cell.width - Search_LeftMargin;
        lineView.y = cell.height - 1;
        lineView.height = 1;
        [cell.contentView addSubview:lineView];
        
    }
    cell.textLabel.text = self.searchHistoryArr[indexPath.row];
    cell.imageView.image = [UIImage imageNamed:@"search_history"];
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    self.searchBar.text = cell.textLabel.text;
    [self searchBarSearchButtonClicked:self.searchBar];
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    //滑动键盘消失
    if (self.keyBoardShowing)
    {
        //调整搜索建议内边距
        self.SuggestViewController.tableView.contentInset = UIEdgeInsetsMake(-30, 0, 30, 0);
        [self.searchBar resignFirstResponder];
    }
}

-(void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if ([self.SearchDelegate respondsToSelector:@selector(searchVC:searchTextDidChange:searchText:)])
    {
        [self.SearchDelegate searchVC:self searchTextDidChange:searchBar searchText:searchText];
    }
    
    //如果有搜索文本且显示搜索建议 则隐藏主view
    self.baseTableview.hidden = searchText.length && self.showSearchSuggestWhenSearchTextChanged;
    
    //根据输入的文本显示建议条件
    self.SuggestViewController.view.hidden = !searchText.length ||!self.showSearchSuggestWhenSearchTextChanged;
    
    if (self.SuggestViewController.view.hidden == YES)
    {
        //清空搜索建议
        self.searchSuggestions = nil;
    }
    [self.view bringSubviewToFront:self.SuggestViewController.view];
    
}


-(void)deleteHistorycell:(UIButton*)sender
{
    UITableViewCell *cell = (UITableViewCell *)sender.superview;
    [self.searchHistoryArr removeObject:cell.textLabel.text];
    [NSKeyedArchiver archiveRootObject:self.searchHistoryArr toFile:_searchHistoryCachesPath];
    [self setCNKIBottomSearchHistoryStyle:CNKISearchHistoryStyleCell];
    [self.baseTableview reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


@end
